package spacegame.model;

import java.util.List;

import org.andengine.extension.physics.box2d.PhysicsWorld;

import spacegame.interfaces.ISpaceObject;
import spacegame.interfaces.ISpaceWorldContainer;
import spacegame.resources.ResourceFactory;
import spacegame.resources.ResourceFactory.PlanetType;

import com.badlogic.gdx.math.Vector2;

/**
 * Класс модель космического мира. Бизнес-логика
 * @author Muiota Betarho
 *
 */
public class SpacePhysicsWorld extends PhysicsWorld {

	
	private SpaceObjectCollection m_spaceObjectCollection;
	private SpaceShipItem m_shipModel;
	/**
	 * Класс модель космического мира. Бизнес-логика
	 * @param pGravity - вектор гравитации
	 * @param pAllowSleep - доступно засыпание
	 */
	public SpacePhysicsWorld(Vector2 pGravity, boolean pAllowSleep  ) {
		super(pGravity, pAllowSleep);
	
	}

	
	/**
	 * Метод инициализации космического мира
	 * @param pContainer - класс контейнер для текстур
	 * @param pResorceFactory - ресурсы
	 */
	public void Init(ISpaceWorldContainer pContainer,ResourceFactory pResorceFactory)
	{
		
		m_spaceObjectCollection = new SpaceObjectCollection(pContainer,pResorceFactory);
		m_shipModel = new SpaceShipItem(440, 160, pResorceFactory, pContainer);
	}
	
	public void CreateScene()
	{
		m_spaceObjectCollection.CreateSunObject(0, 0);
		m_spaceObjectCollection.CreatePlanetObject(500, 0, PlanetType.Venus , 1);
		m_spaceObjectCollection.CreatePlanetObject(-900, 900, PlanetType.Jupiter , 1);
		m_spaceObjectCollection.CreatePlanetObject(-1500, 0, PlanetType.Mars , 1);
	}
	
	
	@Override
	public void onUpdate(float pSecondsElapsed) {
		//Log.i("elapsed", Float.toString(pSecondsElapsed));
		if (pSecondsElapsed>0.8f)
		pSecondsElapsed = 0.8f;
		onMainUpdate(pSecondsElapsed);
		super.onUpdate(pSecondsElapsed);
	}	
	
	public void CreateSpaceObject(final float pX, final float pY)
	{
		m_spaceObjectCollection.CreateSpaceObject(pX, pY);
	}

	public void ApplyEngineForce(final float pX, final float pY)
	{
	m_shipModel.ApplyEngineForce(pX, pY);		
	}	
	private void onMainUpdate(float pSecondsElapsed) {
		//Forces for ship direction

		
		m_shipModel.Update(pSecondsElapsed);
		
		final List<ISpaceObject> _collection = m_spaceObjectCollection.GetCollection();
		final Vector2 _shipCenter = m_shipModel.BodyCenter;
		for (ISpaceObject _spaceObject : _collection) {
			{
				
				_spaceObject.Update(pSecondsElapsed);
				 Vector2 _pos = _spaceObject.GetPosition();
				 Vector2 _distance = _pos.sub(_shipCenter);
				 final float _length = _distance.len2();
				 if (_length == 0 )
					 continue;
				 _distance = _distance.nor();
				
				_distance.mul(_spaceObject.GetMass()*0.1f/(_length+40));
					m_shipModel.ApplyForce(_distance, _shipCenter);
				
			}
			
		}
	}
}
